#!/usr/bin/env python
#coding=utf-8
import sys,time
sys.path.append('/home/jay/xiaojaylib/gae')
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'gae_manager.settings'
from gae_manager.host.models import Project

COL_NONE = "\033[0m"
COL_RED  = "\033[0;31;48m"

import subprocess
command = 'appcfg.py --passin --email=%s --application=%s --no_cookies update %s'

project_name = 'mail_server2'
project = Project.objects.get(name = project_name)
path = project.path

for app in project.app_set.filter(created_at__gt='2009-12-21 02:00:00'):
  account = app.account  
  complete_command = command%(account.email, app.app_id, path)

  print '\n%s:%s %s %s'%(app.app_id, COL_RED, complete_command, COL_NONE)

  p = subprocess.Popen(complete_command, shell=True, stdin=subprocess.PIPE)
  p.communicate(account.password)
  
  print
  '''
  time.sleep(10)
  import urllib
  import urllib2

  EMAILHTML = 'email.html'
  email_html = open(EMAILHTML).read()
  SUBJECT = '${name}:-)为你送上圣诞节送礼指南（淘宝篇）!'
  
  url = 'http://%s.appspot.com/post_ad'%app.app_id
  print url
  values = {'campaign': '圣诞',
            'subject': SUBJECT,
            'plain': '$email 你好',
            'html': email_html}

  data = urllib.urlencode(values)
  req = urllib2.Request(url, data)
  response = urllib2.urlopen(req)
  the_page = response.read()
  print the_page.split('br')[1]
  '''
